<template>
  <div class="al-container">
    <div class="chat-container">
      <div class="chat-content">
        <div
          class="chat-text-container"
          v-for="(item, index) in chatData"
          :key="index"
          :class="item.type === 'response' ? 'left' : 'right'"
        >
          <el-card class="content-card">{{ item.content }}</el-card>
        </div>
      </div>
      <div class="chat-history">
        <div class="chat-history-title-container">
          <span class="chat-history-title">历史会话</span>
        </div>
        <div
          class="chat-history-card-container"
          v-for="(item, index) in sessionTopic"
          :key="index"
        >
          <el-card
            class="chat-history-card"
            v-if="item.show"
            style="margin-bottom: 10px"
            >{{ item.topic }}</el-card
          >
        </div>
      </div>
    </div>
    <div class="chat-input-container">
      <el-row :gutter="20">
        <el-col :span="3">
          <div class="theme-container">
            <el-button
              type="primary"
              round
              icon="el-icon-circle-plus-outline"
              @click="clearSession"
              >新建会话</el-button
            >
          </div></el-col
        >
        <el-col :span="18">
          <!-- 需要响应原生的回车事件 -->
          <!-- TODO:需要将input和i标签的click事件对应上 -->
          <el-input
            placeholder="请输入您的问题"
            class="input-content-textarea"
            style="width: 100%; font-size: 16px"
            v-model="inputText"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 5 }"
            @keyup.enter.native="sendRequest2"
          ></el-input>
        </el-col>
        <el-col :span="3">
          <div class="sendText-container">
            <i
              class="el-icon-s-promotion sendText-button"
              @click="sendRequest2"
            ></i>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { wenXinBotApi, wenXinBotApi2 } from "@/apis/wordDetectionApi";
@Component({
  name: "AlView",
})
export default class AlView extends Vue {
  mounted() {} // 对话的数据格式
  chatData = [
    {
      type: "response",
      content: "您好，请问您有什么想问的吗？",
    },
  ];
  inputText: string = "";
  done: boolean = false;
  sessionTopic: [
    {
      topic: string;
      show: boolean;
    }
  ] = [] as any;
  isFirst: boolean = true;

  // 发送请求
  async sendRequest2() {
    if (this.inputText == "" || this.inputText == "\n") {
      this.$message.warning("请先输入您的问题");
      return;
    } else {
      // 我应该先将问题添加到数据中，在等待服务器的回复
      this.chatData.push({
        type: "request",
        content: this.inputText,
      });
      let text = this.inputText;
      // 表示第一次检索过将检索的内容放到sessionTopic中
      if (this.isFirst == true) {
        this.sessionTopic.push({
          topic: text.slice(0, 10),
          show: true,
        });
        this.isFirst = false;
      }
      // 每次问题发送之后需要清空输入框中的内容
      this.inputText = "";
      try {
        let response = await wenXinBotApi2(text, "botChat", 1);
        if (!response.ok) {
          throw new Error("请求失败");
        }
        // 先添加回答
        this.chatData.push({
          type: "response",
          content: "",
        });
        const reader = response.body!.getReader();
        let len = this.chatData.length;
        let decoder = new TextDecoder();
        let result = true;
        while (result) {
          let { done, value } = await reader.read();
          if (done) {
            result = false;
            break;
          }
          let buffer = decoder.decode(value);
          let events = buffer.split("\n");
          if (events.length > 1) {
            events.slice(0, -1).forEach((event) => {
              const eventData = event.replace(/^data: /, "");
              const jsonData = JSON.parse(eventData);
              if (jsonData && jsonData.result) {
                this.chatData[len - 1].content += jsonData.result;
              }
            });
          }
        }
      } catch (err) {
        console.log(err);
      }
    }
  }

  // 发送请求
  // async sendRequest3() {
  //   if (this.inputText == "" || this.inputText == "\n") {
  //     this.$message.warning("请先输入您的问题");
  //     return;
  //   } else {
  //     // 我应该先将问题添加到数据中，在等待服务器的回复
  //     this.chatData.push({
  //       type: "request",
  //       content: this.inputText,
  //     });
  //     let text = this.inputText;
  //     // 表示第一次检索过将检索的内容放到sessionTopic中
  //     if (this.isFirst == true) {
  //       this.sessionTopic.push({
  //         topic: text.slice(0, 10),
  //         show: true,
  //       });
  //       this.isFirst = false;
  //     }
  //     // 每次问题发送之后需要清空输入框中的内容
  //     this.inputText = "";
  //     wenXinBotApi2(text, "botChat", 1)
  //       .then((response) => {
  //         if (!response.ok) {
  //           throw new Error("请求失败");
  //         }
  //         return response.body;
  //       })
  //       .then((body) => {
  //         const reader = body!.getReader();
  //         // 读取数据流
  //         function read() {
  //           return reader.read().then(({ done, value }) => {
  //             // 检查是否读取完毕
  //             if (done) {
  //               console.log("已传输完毕");
  //               return;
  //             }
  //             // 处理每个数据块
  //             console.log("收到的数据:", value);
  //             // 继续读取下一个数据块
  //             read();
  //           });
  //         }
  //         // 开始读取数据流
  //         read();
  //       })
  //       .catch((err) => {
  //         console.log(err);
  //       });
  //   }
  // }

  // async sendRequest4() {
  //   if (this.inputText == "" || this.inputText == "\n") {
  //     this.$message.warning("请先输入您的问题");
  //     return;
  //   } else {
  //     // 我应该先将问题添加到数据中，在等待服务器的回复
  //     this.chatData.push({
  //       type: "request",
  //       content: this.inputText,
  //     });
  //     let text = this.inputText;
  //     // 表示第一次检索过将检索的内容放到sessionTopic中
  //     if (this.isFirst == true) {
  //       this.sessionTopic.push({
  //         topic: text.slice(0, 10),
  //         show: true,
  //       });
  //       this.isFirst = false;
  //     }
  //     // 每次问题发送之后需要清空输入框中的内容
  //     this.inputText = "";
  //     const response = await fetch("https://luckycola.com.cn/ai/wxChatV2", {
  //       method: "POST",
  //       headers: {
  //         "Content-Type": "application/json",
  //       },
  //       body: JSON.stringify({
  //         ques: text,
  //         appKey: "65a6b59a4ea016820beda04d",
  //         uid: "HqoSBW1705424248424MFUAsVDqsU",
  //         isLongChat: 1,
  //         chatModel: "botChat",
  //         isStream: true,
  //       }),
  //     });
  //     const reader = response.body!.getReader();
  //     const textDecoder = new TextDecoder();
  //     while (1) {
  //       const { done, value } = await reader.read();
  //       if (done) {
  //         break;
  //       }
  //       const str = textDecoder.decode(value);
  //       console.log(str);
  //     }
  //   }
  // }

  // 点击新建会话清空当前页面的所有内容
  clearSession() {
    this.chatData = [
      {
        type: "response",
        content: "您好，请问您有什么想问的吗？",
      },
    ];
    this.isFirst = true;
  }
}
</script>


<style lang="scss" scoped>
@import "@/assets/styles/themes.scss";
.al-container {
  width: 1300px;
  min-height: 680px;
  height: 100vh;
  margin: 0 auto;
  box-sizing: border-box;
  box-shadow: 4px 4px 8px rgba(0, 0, 0, 0.113),
    -4px -4px 8px rgba(0, 0, 0, 0.113);
  border-radius: 8px;
  height: 80vh;
  display: flex;
  justify-content: center;
  padding: 15px;
  @include useTheme {
    background-color: getVar("divColor");
    color: getVar("textColor");
  }
  .chat-container {
    width: 100%;
    height: 100%;
    display: flex;
    .chat-content {
      width: 80%;
      min-height: 100%;
      border-right: 1px solid gray;
      padding: 10px;
      overflow-y: auto;
      // 单独让回答在左边,左右两侧的回答的显示框的样式不一样
      .left {
        display: flex;
        justify-content: flex-start;
        margin-left: 20px;
        margin-right: 50px;
        .content-card {
          text-align: left;
          animation: text-anim 0.5s ease-in-out forwards;
          ::v-deep(.el-card__body) {
            padding: 10px;
            border-radius: 8px;
            background-color: #299fba;
            color: #fff;
            width: fit-content;
          }
        }
      }
      // 单独让提问在右边
      .right {
        display: flex;
        justify-content: flex-end;
        margin-right: 20px;
        margin-left: 50px;
        .content-card {
          text-align: right;
          ::v-deep(.el-card__body) {
            padding: 10px;
            border-radius: 8px;
            background-color: #006c85;
            color: #fff;
            width: fit-content;
          }
        }
      }
      // 选中所有的card进行修改
      .chat-text-container {
        margin-bottom: 10px;
      }
      .response {
      }
      .left {
      }
      .right {
      }
    }
    .chat-history {
      width: 20%;
      height: 100%;
      border-left: 1px solid gray;
      padding: 10px;
      overflow-y: auto;
      .chat-history-title-container {
        width: 100%;
        height: 20px;
        margin-bottom: 10px;
        .chat-history-title {
          font-size: 16px;
          font-weight: bold;
        }
      }
      .chat-history-card {
        ::v-deep(.el-card__body) {
          padding: 12px;
        }
      }
    }
  }

  .chat-input-container {
    width: 1300px;
    min-height: 80px;
    height: auto;
    max-height: 300px;
    position: fixed;
    bottom: 20px;
    background-color: rgb(246, 251, 255);
    box-shadow: 4px 4px 20px rgba(164, 206, 238, 0.25),
      -4px -4px 20px rgba(164, 206, 238, 0.25);
    padding: 10px;
    border-radius: 4px;
    // border: 1px solid #dcdfe6;
    @include useTheme {
      background-color: getVar("divColor");
      color: getVar("textColor");
    }
    .input-content-textarea {
      // @include useTheme {
      //   background-color: getVar("divColor");
      // }
      border-radius: 4px;
      background-color: #fff;
      border: 1px solid #dcdfe6;
      box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
      transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
      font-size: 14px;
      &:hover,
      &:focus {
        border-color: #409eff;
      }
    }
    .sendText-container {
      width: 100%;
      text-align: left;
      display: flex;
      height: 40px;
      align-items: center;
      .sendText-button {
        font-size: 28px;
        cursor: pointer;
        &:hover {
          color: #409eff;
        }
      }
    }
  }
}
@keyframes text-anim {
  from {
    opacity: 0; /* 初始透明度为0 */
    transform: translateX(-10px); /* 初始位置在左边 */
  }

  to {
    opacity: 1; /* 透明度变为1 */
    transform: translateX(0); /* 移动到原来的位置 */
  }
}
</style>